package com.movecar.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.movecar.R;
import com.movecar.model.CloudBeansBean;
import com.movecar.model.FriendsBean;
import com.movecar.model.GroupBean;
import com.movecar.model.GroupMemberBean;
import com.movecar.model.InviteFriendsBean;
import com.movecar.sortlistview.CharacterParser;
import com.movecar.sortlistview.PinyinComparator;
import com.movecar.sortlistview.SideBar;
import com.movecar.sortlistview.SideBar.OnTouchingLetterChangedListener;
import com.movecar.sortlistview.SortGroupMemberAdapter;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.PopupWindowAnimation;
import com.movecar.utils.RequestResultCallback;
import com.movecar.widget.CustomProgressDialog;

/**
 * 好友列表相关(邀请好友、我的好友)
 * 
 * @author Zhao.JQ
 *
 */
public class ActivityAddFriends extends Activity implements OnClickListener {
	private ListView sortListView;
	private SideBar sideBar;
	private TextView dialog;
	private SortGroupMemberAdapter adapter;
	private boolean choose_friends = false;

	// private ClearEditText mClearEditText;
	private CustomProgressDialog progressDialog = null;

	private CloudBeansBean mCloudBeansBean;
	private TextView tvNofriends;
	private FriendsBean mFriendsBean;
	private List<InviteFriendsBean> mFriendsBeanList;
	private List<GroupMemberBean> DateList;
	private String messageId;
	private String applyFlag;
	/**
	 * 上次第一个可见元素，用于滚动时记录标识。
	 */
	private int lastFirstVisibleItem = -1;
	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	private List<GroupMemberBean> SourceDateList;

	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;
	private View mainView;
	private LayoutInflater layoutInflater;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mainView = layoutInflater.inflate(R.layout.activity_add_friends, null);
		setContentView(mainView);
		initViews();
	}

	private void initViews() {
		choose_friends = getIntent().getBooleanExtra("choose_friends", false);
		messageId = getIntent().getStringExtra("messageId");
		TextView main_title = (TextView) findViewById(R.id.title);
		main_title.setText("我的好友");
		Button back = (Button) findViewById(R.id.btn_left);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(this);

		if (!choose_friends) {
			Button right = (Button) findViewById(R.id.btn_right_long);
			right.setBackgroundResource(R.drawable.btn_invitation_friends);
			right.setVisibility(View.VISIBLE);
			right.setOnClickListener(this);
		} else {
			Button right = (Button) findViewById(R.id.btn_right);
			right.setBackgroundResource(R.drawable.btn_confirm);
			right.setVisibility(View.VISIBLE);
			right.setOnClickListener(this);
		}

		// titleLayout = (RelativeLayout) findViewById(R.id.title_layout);
		// title = (TextView) this.findViewById(R.id.title_layout_catalog);
		tvNofriends = (TextView) this.findViewById(R.id.title_layout_no_friends);
		// 实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();

		pinyinComparator = new PinyinComparator();

		sideBar = (SideBar) findViewById(R.id.sidrbar);
		dialog = (TextView) findViewById(R.id.dialog);
		sideBar.setTextView(dialog);

		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = adapter.getPositionForSection(s.charAt(0));
				if (s.contains("@")) {
					sortListView.setSelection(0);
				} else if (position != -1) {
					sortListView.setSelection(position);
				}

			}
		});

		sortListView = (ListView) findViewById(R.id.country_lvcountry);
		sortListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (choose_friends) {

				} else {
					if ("好友申请".equals(((GroupMemberBean) adapter.getItem(position)).getSortLetters())) {
						Intent intent = new Intent().setClass(ActivityAddFriends.this, FriendApplyActivity.class);
						startActivity(intent);
					} else {
						// 这里要利用adapter.getItem(position)来获取当前position所对应的对象
						Intent intent = new Intent().setClass(ActivityAddFriends.this, FriendPersonalInfActivity.class);
						intent.putExtra("shareUserId", ((GroupMemberBean) adapter.getItem(position)).getFriendId());
						startActivity(intent);
					}
				}

			}
		});

		// mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);

		// 根据输入框输入值的改变来过滤搜索
		// mClearEditText.addTextChangedListener(new TextWatcher() {
		//
		// @Override
		// public void onTextChanged(CharSequence s, int start, int before, int
		// count) {
		// // 这个时候不需要挤压效果 就把他隐藏掉
		// titleLayout.setVisibility(View.GONE);
		// // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
		// filterData(s.toString());
		// }
		//
		// @Override
		// public void beforeTextChanged(CharSequence s, int start, int count,
		// int after) {
		//
		// }
		//
		// @Override
		// public void afterTextChanged(Editable s) {
		// }
		// });
	}

	@Override
	protected void onResume() {
		startProgressDialog();
		if (choose_friends) {
			getInviteFriends();
		} else {
			getFriends();
		}

		super.onResume();
	}

	/**
	 * 为ListView填充数据
	 * 
	 * @param date
	 * @return
	 */
	private List<GroupMemberBean> filledData(List<GroupMemberBean> data) {
		List<GroupMemberBean> mSortList = new ArrayList<GroupMemberBean>();

		for (int i = 0; i < data.size(); i++) {
			GroupMemberBean sortModel = new GroupMemberBean();
			sortModel.setName(data.get(i).getName());
			sortModel.setIcon(data.get(i).getIcon());
			sortModel.setFriendId(data.get(i).getFriendId());
			// 汉字转换成拼音
			String pinyin = characterParser.getSelling(data.get(i).getName());
			String sortString = pinyin.substring(0, 1).toUpperCase();
			if (sortModel.getName().indexOf("好友申请") > 0 && !choose_friends) {
				sortModel.setSortLetters("好友申请");
			} else
			// 正则表达式，判断首字母是否是英文字母
			if (sortString.matches("[A-Z]")) {
				sortModel.setSortLetters(sortString.toUpperCase());
			} else {
				sortModel.setSortLetters("#");
			}

			mSortList.add(sortModel);
		}
		return mSortList;

	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * 
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		List<GroupMemberBean> filterDateList = new ArrayList<GroupMemberBean>();

		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = SourceDateList;
			tvNofriends.setVisibility(View.GONE);
		} else {
			filterDateList.clear();
			for (GroupMemberBean sortModel : SourceDateList) {
				String name = sortModel.getName();
				if (name.indexOf(filterStr.toString()) != -1
						|| characterParser.getSelling(name).startsWith(filterStr.toString())) {
					filterDateList.add(sortModel);
				}
			}
		}

		adapter.updateListView(filterDateList);
		if (filterDateList.size() == 0) {
			tvNofriends.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 根据ListView的当前位置获取分类的首字母的Char ascii值
	 */
	public int getSectionForPosition(int position) {
		return SourceDateList.get(position).getSortLetters().charAt(0);
	}

	/**
	 * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
	 */
	public int getPositionForSection(int section) {
		for (int i = 0; i < SourceDateList.size(); i++) {
			String sortStr = SourceDateList.get(i).getSortLetters();
			char firstChar = sortStr.toUpperCase().charAt(0);
			if (firstChar == section) {
				return i;
			}
		}
		return -1;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// 账号管理
		case R.id.btn_left:
			finish();
			break;
		case R.id.btn_right_long:
			startActivity(new Intent(getApplicationContext(), ActivityInvitationFriends.class));
			break;
		case R.id.btn_right:
			startProgressDialog();
			if (TextUtils.isEmpty(adapter.getFriends().toString())) {
				Alert.warn(ActivityAddFriends.this, "请选择好友邀请！");
			} else {
				inviteFriend(messageId, adapter.getFriends().toString());
			}

			break;
		default:
			break;
		}
	}

	/**
	 * 邀请好友
	 * 
	 */
	@SuppressWarnings("unchecked")
	private void inviteFriend(String messageId, String friendList) {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "inviteFriendNew1")); // 添加要传递的参数

		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("messageId", messageId));
		params.add(new BasicNameValuePair("friendList", friendList));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {

				String result = (String) object;
				Gson gson = new Gson();
				try {
					mCloudBeansBean = gson.fromJson(result, CloudBeansBean.class);
				} catch (Exception e) {
					return;
				}
				if ("0".equals(mCloudBeansBean.getResultCode())) {
					if (!TextUtils.isEmpty(mCloudBeansBean.getCoinAlert())) {
						new PopupWindowAnimation(mainView, ActivityAddFriends.this);
					}
					if (!"".equals(mCloudBeansBean.getReturnMsg())) {
						// CustomDialog.Builder customBuilder = new
						// CustomDialog.Builder(ActivityAddFriends.this);
						// ImageView img = new
						// ImageView(ActivityAddFriends.this);
						// img.setImageResource(R.drawable.ic_launcher);
						// customBuilder.setImgIcon(img).setMessage(mCloudBeansBean.getReturnMsg())
						//
						// .setPositiveButton("确认", new
						// DialogInterface.OnClickListener() {
						// @Override
						// public void onClick(DialogInterface dialog, int
						// which) {
						//
						// dialog.dismiss();
						//
						// }
						// });
						// customBuilder.create().show();
						Alert.warn(ActivityAddFriends.this, mCloudBeansBean.getReturnMsg());
					} else {
						Alert.info(ActivityAddFriends.this, "邀请成功");
					}
					stopProgressDialog();
					finish();

				} else {
					stopProgressDialog();
					Alert.error(ActivityAddFriends.this, result);
				}
			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.error(ActivityAddFriends.this, "与服务器连接失败，请检查网络");

			}
		}, GroupBean.class, AppConfig.USER).execute(params);
	}

	/**
	 * 我的-我的好友调用接口
	 */
	@SuppressWarnings("unchecked")
	private void getFriends() {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "queryFriendListNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));

		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {

				stopProgressDialog();
				String result = (String) object;
				Gson gson = new Gson();
				try {
					mFriendsBean = gson.fromJson(result, FriendsBean.class);
				} catch (Exception e) {
					return;
				}
				if (null != mFriendsBean) {
					Type type = new TypeToken<List<InviteFriendsBean>>() {
					}.getType();
					Gson gson2 = new Gson();
					String friends = (String) mFriendsBean.getFriendArr();
					Object fromJson = gson2.fromJson(friends, type);
					Log.e("applyFlag", mFriendsBean.getApplyFlag());
					applyFlag = mFriendsBean.getApplyFlag();

					try {
						mFriendsBeanList = (List<InviteFriendsBean>) fromJson;
					} catch (Exception e) {
						return;
					}
				}
				DateList = new ArrayList<GroupMemberBean>();
				// 如果没有好友申请
				if ("".equals(applyFlag)) {
					for (int i = 0; i < mFriendsBeanList.size(); i++) {
						GroupMemberBean bean = null;
						if (i < mFriendsBeanList.size()) {
							bean = new GroupMemberBean();
							bean.setName((mFriendsBeanList.get(i).getNickname()));
							bean.setIcon(mFriendsBeanList.get(i).getIcon());
							bean.setFriendId(mFriendsBeanList.get(i).getFriendId());
						}
						DateList.add(bean);

					}
					// 有好友申请
				} else {

					for (int i = 0; i < mFriendsBeanList.size() + 1; i++) {
						GroupMemberBean bean = null;
						if (i < mFriendsBeanList.size()) {
							bean = new GroupMemberBean();
							bean.setName((mFriendsBeanList.get(i).getNickname()));
							bean.setIcon(mFriendsBeanList.get(i).getIcon());
							bean.setFriendId(mFriendsBeanList.get(i).getFriendId());
						} else if (i == mFriendsBeanList.size()) {
							bean = new GroupMemberBean();
							bean.setName((mFriendsBean.getApplyFlag()));
							bean.setIcon(mFriendsBean.getFriendApplyIcon());

						}
						DateList.add(bean);

					}
				}

				SourceDateList = filledData(DateList);
				// 根据a-z进行排序源数据
				Collections.sort(SourceDateList, pinyinComparator);

				adapter = new SortGroupMemberAdapter(ActivityAddFriends.this, SourceDateList);
				if (choose_friends) {
					adapter.setCheckAble(choose_friends);
				}
				sortListView.setAdapter(adapter);

			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();

				Alert.error(ActivityAddFriends.this, "与服务器连接失败，请检查网络");
			}
		}, GroupBean.class, AppConfig.USER).execute(params);
	}

	/**
	 * 好友邀请调用接口
	 */
	@SuppressWarnings("unchecked")
	private void getInviteFriends() {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "queryInviteFriendListNew2")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;

				Gson gson = new Gson();
				try {
					mFriendsBean = gson.fromJson(result, FriendsBean.class);
				} catch (Exception e) {
					return;
				}
				if (null != mFriendsBean) {
					Type type = new TypeToken<List<InviteFriendsBean>>() {
					}.getType();
					Gson gson2 = new Gson();
					String friends = (String) mFriendsBean.getFriendArr();
					Object fromJson = gson2.fromJson(friends, type);

					try {
						mFriendsBeanList = (List<InviteFriendsBean>) fromJson;
					} catch (Exception e) {
						return;
					}
				}

				DateList = new ArrayList<GroupMemberBean>();

				for (int i = 0; i < mFriendsBeanList.size(); i++) {
					GroupMemberBean bean = null;
					bean = new GroupMemberBean();
					bean.setName((mFriendsBeanList.get(i).getNickname()));
					bean.setIcon(mFriendsBeanList.get(i).getIcon());
					bean.setFriendId(mFriendsBeanList.get(i).getFriendId());

					DateList.add(bean);

				}

				SourceDateList = filledData(DateList);
				// 根据a-z进行排序源数据
				Collections.sort(SourceDateList, pinyinComparator);

				adapter = new SortGroupMemberAdapter(ActivityAddFriends.this, SourceDateList);
				if (choose_friends) {
					adapter.setCheckAble(choose_friends);
				}
				sortListView.setAdapter(adapter);

			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();

				Alert.error(ActivityAddFriends.this, "与服务器连接失败，请检查网络");
			}
		}, GroupBean.class, AppConfig.USER).execute(params);
	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}
}
